<script setup lang="ts">
import { ref } from 'vue'
import type { Role } from '@/apis/acl/role/type'
import { addRoleService, updateRoleService } from '@/apis/acl/role'
const dialogVisible = ref(false)

// 初始化参数
const roleParam = ref<Role>({
  id: '',
  roleName: ''
})
// 表单规则
const rules = {
  roleName: [
    { required: true, message: '请输入职位名称', trigger: 'blur' },
    {
      validator: (rule: any, value: any, callback: any) => {
        if (value.length < 5 || value.length > 15) {
          callback(new Error('职位名称长度在5-15之间'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}
const open = (row: Role) => {
  dialogVisible.value = true
  if (row.id) {
    Object.assign(roleParam.value, row)
  } else {
    Object.assign(roleParam.value, {
      id: '',
      roleName: ''
    })
  }
}
// 绑定表单
const formRef = ref()
// 确认
const emits = defineEmits(['addRole'])
const onConfirm = async () => {
  await formRef.value.validate()
  if (roleParam.value.id) {
    await updateRoleService(roleParam.value)
    emits('addRole', 'add')
  } else {
    await addRoleService(roleParam.value)
    emits('addRole', 'update')
  }
  dialogVisible.value = false
}
// 关闭
const closeDialog = () => {
  formRef.value.resetFields()
}

defineExpose({
  open
})
</script>

<template>
  <el-dialog
    v-model="dialogVisible"
    :title="roleParam.id ? '编辑职位' : '添加职位'"
    @closed="closeDialog"
  >
    <template #default>
      <el-form :model="roleParam" :rules="rules" ref="formRef" status-icon>
        <el-form-item label="职位名称" prop="roleName">
          <el-input
            placeholder="请输入职位名称"
            v-model="roleParam.roleName"
          ></el-input>
        </el-form-item>
      </el-form>
    </template>
    <template #footer>
      <el-button type="primary" @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" @click="onConfirm">确定</el-button>
    </template>
  </el-dialog>
</template>

<style scoped lang="scss"></style>
